# -*- coding:utf-8 -*-
import time
import sys
import socket
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QLabel, QLineEdit, QPushButton,
    QTextEdit, QVBoxLayout, QHBoxLayout, QWidget, QFormLayout, QSpinBox, QInputDialog
)
from PyQt5.QtCore import Qt
import core.data_handler as hj212
import util.fun_log as log


class HJ212Simulator(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Tsingluo-HJ212协议数据模拟器")
        self.setGeometry(100, 100, 800, 600)

        self.param_inputs = {}  # 存储用户输入的参数

        main_layout = QHBoxLayout()

        # 布局
        self.left_layout = QVBoxLayout()
        self.right_layout = QVBoxLayout()

        # 服务端设置
        server_layout = QFormLayout()
        self.ip_input = QLineEdit("127.0.0.1")
        self.port_input = QSpinBox()
        self.port_input.setRange(1, 65535)
        self.port_input.setValue(9999)

        server_layout.addRow("服务端 IP:", self.ip_input)
        server_layout.addRow("端口号:", self.port_input)
        self.left_layout.addLayout(server_layout)

        self.param_layout = QFormLayout()
        self.left_layout.addLayout(self.param_layout)

        # 默认参数
        self.default_params = {
            "ST": "59",
            "MN": "130481LBYMH001",
            "PW": "123456",
            "Flag": "5",
            "QN": "20241206000000",  # 假设QN是时间戳
        }

        # 预设参数（可以直接显示在界面上）
        for key, value in self.default_params.items():
            input_field = QLineEdit(value)
            self.param_inputs[key] = input_field
            self.param_layout.addRow(key, input_field)

        # 预设的CP选项
        self.cp_options = {
            "w01001-Min": "6.9",
            "w01001-Max": "7.2",
            "w01018-Min": "70.0",
            "w01018-Avg": "72.4",
        }

        # 添加预设的选项
        for key, value in self.cp_options.items():
            input_field = QLineEdit(value)
            self.param_inputs[key] = input_field
            self.param_layout.addRow(key, input_field)
        # 数据显示区
        self.send_box = QTextEdit()
        self.receive_box = QTextEdit()
        self.send_box.setPlaceholderText("待发送数据")
        self.receive_box.setPlaceholderText("接收数据")
        self.receive_box.setReadOnly(True)

        self.right_layout.addWidget(QLabel("发送框:"))
        self.right_layout.addWidget(self.send_box)
        self.right_layout.addWidget(QLabel("接收框:"))
        self.right_layout.addWidget(self.receive_box)

        # 添加自定义属性按钮
        self.add_button = QPushButton("添加自定义参数")
        self.add_button.clicked.connect(self.add_custom_param)
        self.right_layout.addWidget(self.add_button)

        # 提交按钮
        self.submit_button = QPushButton("提交")
        self.submit_button.clicked.connect(self.submit_data)
        self.right_layout.addWidget(self.submit_button)


        # 将左右布局分别添加到主布局中
        main_layout.addLayout(self.left_layout)
        main_layout.addLayout(self.right_layout)

        self.setLayout(main_layout)

    def append_to_send_box(self, message):
        """追加消息到发送框"""
        current_text = self.send_box.toPlainText()
        self.send_box.setText(current_text + message)

    def append_to_receive_box(self, message):
        """追加消息到接收框"""
        current_text = self.receive_box.toPlainText()
        self.receive_box.setText(current_text + message)

    def add_custom_param(self):
        """允许用户添加自定义的key-value"""
        key, ok = QInputDialog.getText(self, '添加参数', '请输入参数名称:')
        if ok and key:
            value, ok = QInputDialog.getText(self, '添加参数', f'请输入 {key} 的值:')
            if ok and value:
                # 将新键值对加入到字典中
                input_field = QLineEdit(value)
                self.param_inputs[key] = input_field
                self.param_layout.addRow(key, input_field)

    def submit_data(self):
        """获取所有参数并发送"""
        DIC_HJ212_2017 = {}
        for key, input_field in self.param_inputs.items():
            DIC_HJ212_2017[key] = input_field.text()

        # 打印输出数据
        print("最终发送的数据:")
        print(DIC_HJ212_2017)

        # 发送数据
        self.send_data(DIC_HJ212_2017)

    def generate_message(self, data):
        """根据输入生成待发送的 HJ212 消息"""
        print("generate_message")
        print(data)

        # 提取基本参数
        params = {key: field for key, field in data.items()}

        # 初始化消息字典
        DIC_HJ212_2017 = {}

        # 设置固定的基本字段
        DIC_HJ212_2017['QN'] = params.get("QN", "")  # 获取时间戳
        DIC_HJ212_2017['ST'] = params.get("ST", "")  # 设置 ST 参数
        DIC_HJ212_2017['CN'] = 2011  # 设置 CN
        DIC_HJ212_2017['PW'] = params.get("PW", "")  # 设置 PW
        DIC_HJ212_2017['MN'] = params.get("MN", "")  # 设置 MN
        DIC_HJ212_2017['Flag'] = params.get("Flag", "")  # 设置 Flag

        # 初始化 CP 字段
        DIC_HJ212_2017['CP'] = {}

        # 为 CP 添加 DataTime
        DIC_HJ212_2017['CP'][0] = {}
        DIC_HJ212_2017['CP'][0]['DataTime'] = DIC_HJ212_2017['QN'][0:14]  # 获取时间戳的前14位

        # 物质及其对应的参数
        substances = [
            {"name": "w01001", "type": "PH值", "fields": ["Min", "Max"]},
            {"name": "w01018", "type": "化学需氧量", "fields": ["Min", "Avg"]},
            # 可以继续添加其他物质的字典
        ]

        # 根据物质和字段添加 CP 信息
        for index, substance in enumerate(substances, start=1):
            DIC_HJ212_2017['CP'][index] = {}
            for field in substance["fields"]:
                key = f"{substance['name']}-{field}"
                value = float(params.get(key, 0))  # 获取对应字段的值，并转为 float 类型
                DIC_HJ212_2017['CP'][index][key] = value

        encoded_message = hj212.encode(DIC_HJ212_2017)
        return encoded_message

    def send_data(self, data):
        """将数据发送到指定服务器"""
        # 假设目标服务器地址和端口
        host = self.ip_input.text()
        port = self.port_input.value()

        # 使用socket发送数据
        try:
            # 创建TCP套接字
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.connect((host, port))

                # 将字典数据转换为JSON字符串
                data = self.generate_message(data)
                print(data)
                # 将字典数据转换为JSON字符串，并编码为字节流
                # message_json = json.dumps(data)  # 将字典转换为 JSON 字符串
                # 显示发送的数据和时间戳
                timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                send_message = f"时间戳: {timestamp}\n发送的数据: {data}\n"
                self.append_to_send_box(send_message)

                message_bytes = data.encode('utf-8')  # 将字符串编码为字节流

                # 发送数据
                s.sendall(message_bytes)
                # 接收服务器响应
                response = s.recv(1024)
                response_data = response.decode('utf-8')
                # print(f"服务器响应: {response}")

                # 显示接收的数据和时间戳
                timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                receive_message = f"时间戳: {timestamp}\n接收的数据: {response_data}\n"
                self.append_to_receive_box(receive_message)

        except Exception as e:
            print(f"发送数据时发生错误: {e}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = HJ212Simulator()
    window.show()
    sys.exit(app.exec_())
